package com.jnsw.testkotlin

import android.app.Activity
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.KeyEvent
import android.view.View
import app.jnsw.com.database.db.DatabaseHelper
import com.acker.simplezxing.activity.CaptureActivity
import com.allenliu.versionchecklib.AVersionService
import com.allenliu.versionchecklib.HttpRequestMethod
import com.allenliu.versionchecklib.VersionParams
import com.chad.library.adapter.base.BaseQuickAdapter.SLIDEIN_LEFT
import com.jnsw.gps.ChooseMessage
import com.jnsw.gps.GpsService
import com.jnsw.testkotlin.adapter.MyRecyclerAdapter
import com.jnsw.testkotlin.bean.User
import com.jnsw.testkotlin.mainfragment.MainFragment1
import com.jnsw.testkotlin.tab.Tab1Fragment
import com.jnsw.testkotlin.tab.TabActivity
import com.jnsw.testkotlin.updateapp.MyService
import com.jnsw.testkotlin.updateapp.VdialogActivity
import com.lzy.okgo.model.HttpParams
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import rx.Observable
import rx.Subscriber
import rx.Subscription
import java.io.File
import java.util.*


class MainActivity : AppCompatActivity() {
    var mainf = MainFragment1();
    var tf1 = Tab1Fragment();
    var subscription: Subscription? = null;

    var subscriber = object : Subscriber<String>() {
        override fun onCompleted() {
            println("11");
        }

        override fun onError(e: Throwable) {
            println("11");
        }

        override fun onNext(s: String) {
            println("22");
            tv_rx.append(s)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        if (Build.VERSION.SDK_INT >= 21) {
            val decorView = window.decorView
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        }


        val users = ArrayList<User>()
        val user = User()
        user.name = "user1"
        user.age = 26
        users.add(user)
        val user1 = User()
        user1.name = "user11"
        user1.age = 27
        users.add(user1)
        myrecv.setLayoutManager(LinearLayoutManager(this))//必须设置
        var adapter: MyRecyclerAdapter = MyRecyclerAdapter(users)
        adapter.openLoadAnimation(SLIDEIN_LEFT)
        myrecv.adapter = adapter

        var bt = supportFragmentManager.beginTransaction();//新建对象
        bt.add(R.id.mainf, mainf, "mainf");
        bt.add(R.id.mainf, tf1, "tf1");
        bt.hide(tf1)
//      bt.hide(tf1)
        bt.commit();
        EventBus.getDefault().register(this); //接收监听  必须要公共的subscribe接收方法

        var dbhelpter = DatabaseHelper.getInstace(applicationContext);

        var scale = dbhelpter.书签Dao.queryForAll().get(0).scale;
        println("ormlite 书签----------" + scale);
        println("ormlite 数据库名称----------" + dbhelpter.getReadableDatabase().path);


//        registerMessageReceiver();
    }

    fun onClick(v: View) {
        val id = v.id;
        when (id) {
            R.id.btn -> {
                var intent: Intent = Intent(getApplication(), List1Activity::class.java)
                intent.putExtra("username", "userName");
                startActivity(intent)
            }
            R.id.btn_tree -> {
                var intent: Intent = Intent(getApplication(), TreeActivity::class.java)
                intent.putExtra("username", "userName");
                startActivity(intent)
            }
            R.id.btn_camera -> {
                var intent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                startActivityForResult(intent, 1011);
            }
            R.id.btn_drawer -> {
                var intent: Intent = Intent(getApplication(), Main2Activity::class.java)
                startActivity(intent);
                overridePendingTransition(R.anim.activityin, R.anim.activityout);
            }
            R.id.btn_tab -> {
                var intent: Intent = Intent(getApplication(), TabActivity::class.java)
                startActivity(intent);
            }
            R.id.btn_2wm -> {
                var intent: Intent = Intent(getApplication(), CaptureActivity::class.java)
                startActivityForResult(intent, 10012);
            }
            R.id.btn_rx -> {
                println("btn_rx ===========click-------------")
                var observable = Observable.create(object : Observable.OnSubscribe<String> {
                    override fun call(subscriber: Subscriber<in String>) {
                        var dv = 123.036 %1 ;
                        subscriber.onNext("1546222----"+ dv+"--")
                        subscriber.onCompleted()

                    }
                })
                subscription = observable.subscribe(subscriber)

//                MyApplication.getInstance().eventBus.post("1546222----");
                var dv = 123.036 /1 ;
                EventBus.getDefault().post("1546222----"+dv);

            }
            R.id.btn_anim -> {
                var intent: Intent = Intent(getApplication(), AnimActivity::class.java)
                startActivity(intent);
            }
            R.id.btn_viewstub -> {
                var intent: Intent = Intent(getApplication(), ViewStubAvtivity::class.java)
                startActivity(intent);
            }
            R.id.btn_gps -> {

                startService(Intent(applicationContext,
                        GpsService::class.java))


            }
            R.id.btn_fileupload -> {


                var intent: Intent = Intent(getApplication(), FileUploadActivity::class.java)
                startActivity(intent);
            }
            R.id.btn_check -> {
                var path = Environment.getExternalStorageDirectory().getPath() + "/AK/";
                var file = File(path);

                if (!file.exists()) {
                    file.mkdirs();
                }
                val params = HttpParams()
                params.put("type", "android")
                var versionParams = VersionParams().setRequestUrl("http://10.80.5.247:8087/jpushtest/GetNewVersion")
                        .setDownloadAPKPath(path)
                        .setRequestMethod(HttpRequestMethod.POST)
                        .setRequestParams(params)
                        .setCustomDownloadActivityClass(VdialogActivity::class.java);
                intent = Intent(getApplication(), MyService::class.java);
                intent.putExtra(AVersionService.VERSION_PARAMS_KEY, versionParams);
                startService(intent);
            }
        }
    }

    //沉浸式模式
    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        if (hasFocus && Build.VERSION.SDK_INT >= 19) {
            val decorView = window.decorView
            decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1011) {
            println("拍照返回");
            if (resultCode == Activity.RESULT_OK) {//拍照成功
                var bt = supportFragmentManager.beginTransaction();

                bt.hide(mainf);
                bt.show(tf1);
                bt.commit();
                println("拍照返回 ___   OK ");

                if (data != null) { //可能尚未指定intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    //返回
                    if (data.hasExtra("data")) {
//                        val thumbnail = data.getParcelableExtra("data")
                    }
                } else {
                    //由于指定了目标uri，存储在目标uri，intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                    // 通过目标uri，找到图片
                    // 对图片的缩放处理
                    // 操作
                }
            }

        } else if (requestCode == 10012) {
            if (resultCode == Activity.RESULT_OK) {
                System.out.println("erweima         OK--------------");
                var url = data!!.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT);
                tv_rx.setText(url);  //or do sth
                var intent: Intent = Intent(getApplication(), webActivity::class.java)
                intent.putExtra("url", url);
                startActivity(intent);

            } else if (resultCode == RESULT_CANCELED) {
                if (data != null) {
                    System.out.println("erweima         RESULT_CANCELED--------------");
                    // for some reason camera is not working correctly
                    var url = data!!.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT);
                    tv_rx.setText(url);  //or do sth
                    var intent: Intent = Intent(getApplication(), webActivity::class.java)
                    intent.putExtra("url", url);
                    startActivity(intent);
                }
            }


        }
    }

    override fun onDestroy() {
        if (subscription != null) {

            subscription!!.unsubscribe();
        }
        super.onDestroy()
    }


    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {


        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // 创建退出对话框
            val isExit = AlertDialog.Builder(this).create()
            // 设置对话框标题
            isExit.setTitle("系统提示")
            // 设置对话框消息
            isExit.setMessage("确定要退出吗")
            // 添加选择按钮并注册监听
            isExit.setButton(AlertDialog.BUTTON_POSITIVE, "确定", listener)
            isExit.setButton(AlertDialog.BUTTON_NEGATIVE, "取消", listener)
            // 显示对话框
            isExit.show()

        }

        return false
    }

    /**监听对话框里面的button点击事件 */
    internal var listener: DialogInterface.OnClickListener = DialogInterface.OnClickListener { dialog, which ->
        when (which) {
            AlertDialog.BUTTON_POSITIVE// "确认"按钮退出程序
            -> finish()
            AlertDialog.BUTTON_NEGATIVE// "取消"第二个按钮取消对话框
            -> {
            }
            else -> {
            }
        }
    }


    //	  class MessageReceiver : BroadcastReceiver() {
//         var MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
//         var  KEY_TITLE = "title";
//         var  KEY_MESSAGE = "message";
//         var  KEY_EXTRAS = "extras";
//
//         override fun onReceive(context: Context?, intent: Intent?) {
//         try {
//             if (intent != null) {
//                 if ( MESSAGE_RECEIVED_ACTION == intent.action){
//                     var message = intent.getStringExtra(KEY_MESSAGE);
//                     var titlt = intent.getStringExtra(KEY_TITLE);
//                     var extras = intent.getStringExtra(KEY_EXTRAS);
//
//                     Log.d("message","message------------------");
//                 }
//             }
//         }   catch (e:Exception){
//
//         }
//
//         }
//	}
//	fun registerMessageReceiver() {
//		var mMessageReceiver = MessageReceiver();
//		var filter  = IntentFilter();
//		filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
//		filter.addAction("com.example.jpushdemo.MESSAGE_RECEIVED_ACTION");
//		LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
//	}
    /**
     * eventbus 接收 过滤后的Gps坐标点信息
     */
    @Subscribe
    fun receive(message: ChooseMessage) {
    var x = message.point.x;
   var y =  message.point.y;
        Log.d("chooethread - receive",x.toString()+"-=-=---------"+y.toString());
    }




}
